var ctx;
var uname = "";
var type = 0;
var selectRu = [];
var phoneReg = /^(13[0-9]|15[0-9]|18[0-9]|14[578])[0-9]{8}$/;
var emailReg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
var pwdReg = /^(?![^a-zA-Z]+$)(?!\D+$).{8,30}$/; //至少包含字母数字的验证

function setCtx(ctx){
	this.ctx = ctx;
}

var userType = $("#userType").val();
if(userType == 1 ){
	$("#oCompany").show();
}else{
	$("#oCompany").hide();
}

//选择用户类型
$('#userType').change(function(){ 
	$("#userRoles").empty();
	$("#choosedRole").empty();
	
	userType = $(this).children('option:selected').val();
	if(userType == 1 ){
		$("#oCompany").show();
		roleList(1);
	}else{
		$("#oCompany").hide();
		roleList(0);
	}
});

$(function(){
    if(userType == 4){
		$("#userRoles").find(":checkbox").each(function(){  
			$(this).click(function(){
				if(this.checked){
					$(this).parent().parent().siblings().children().children(":checkbox").each(function(){  
//			        	alert(this.id);
			    		if(this.checked){
			    			this.checked = false;   
		    			}
		    		});
				}
		    });
		});
    }
})

function roleList(userType){
	$("#search_condition").val('');
	$.ajax({
		type : "POST",
		url : ctx + "/user/getRoleList",
		cache : false,
		dataType : 'json',
		data: {
			userId : $("#userId").val(),
			userType : userType,
			keyWord : null
		},
		success : function(result) {
			if (result.success) {
				$("#userRoles").html('');
			      var jsonObj=eval("("+result.obj+")");  
			      
			        $.each(jsonObj, function (i, item) {
			        	var html = '<div style="height:40px;line-height:40px;float:left;"><div style="display:inline-block;float:left;">';
			        	html += '<input id="checked" type="hidden" value=' + item.id + '>';
			        	html += '<input id="checked1" type="hidden" value=' + item.roleName + '>';
			        	html += '<input id="roleLen" type="hidden" value='+ jsonObj.length +'>';
			        	if(item.disabled){
			        		html += '<input type="checkbox" style="vertical-align:middle;cursor: pointer;margin-top:-1px;" onclick="checkRu('+item.id +','+"'"+item.roleName +"'"+','+'this'+',' + item.disabled + ');" id="rStatus'+item.id+'" disabled="disabled"/>';
			        	}else{
			        		html += '<input type="checkbox" style="vertical-align:middle;cursor: pointer;margin-top:-1px;" onclick="checkRu('+item.id +','+"'"+item.roleName +"'"+','+'this'+',' + item.disabled + ');" id="rStatus'+item.id+'"/>';
			        	}
			        	html += '</div><div style="vertical-align:middle;float:left;padding-left:5px;">'+item.roleName+'</div></div>';
			        	/*if(i % 2 == 1){
			        		html += '<span></br></span>';
			        	}*/
			        	$("#userRoles").append(html);
			        }); 
			} else {
				layer.msg("操作失败",{
					icon: 2
				});
			}
		}
	});
}

//验证用户名称
function checkUserName(){
	var uname = $("#uname").val();
	//解决ie9以下placeholder与value重复的问题
	if(uname == $("#uname").attr("placeholder")){
		uname = "";
	}
	if(uname == null || uname == ""){
		layer.tips('用户名称不能为空!', '#uname', {
		    tips: 3,
		    time:1000
		});
		return false;
	}else{
		return true;
	}
}


function checkRole(){
	if(selectRu == null || selectRu == "" || selectRu.length == 0){
		layer.msg('请选择角色!',{
			icon: 2,
			time: 1000 //2秒关闭（如果不配置，默认是3秒）
		},function(){
			//parent.layer.close(index); //根据窗口索引关闭窗口   
		});
		return false;
	}else{
		return true;
	}
}

function checkShop(){
	var userType = $("#userType").val();
	if(userType != 3){
		return true;
	}
	
	var selectedShopId = parent.$("#selectedShopId").val();
	if(selectedShopId == null || selectedShopId == "" || selectRu.length == 0){
		layer.msg('请选择店铺!',{
			icon: 2,
			time: 1000 //2秒关闭（如果不配置，默认是3秒）
		},function(){
			//parent.layer.close(index); //根据窗口索引关闭窗口   
		});
		return false;
	}else{
		return true;
	}
}

//验证手机
function checkPhone(){
	 var phone = $("#phone").val();
	//解决ie9以下placeholder与value重复的问题
		if(phone == $("#phone").attr("placeholder")){
			phone = "";
		}

			if(phone == null || phone == ""){
				layer.tips('手机号不能为空', '#phone', {
				    tips: 3,
				    time:1000
				});
				return false;
			}else{
				if(!phoneReg.test(phone)){
					layer.tips('手机号格式错误，请填写正确格式的手机号!', '#phone', {
					    tips: 3,
					    time:1000
					});
					return false;
				}else{
					return true;
				}
			}
		
}

//验证邮箱
function checkEmial(){
	 var email = $("#email").val();
	//解决ie9以下placeholder与value重复的问题
		if(email == $("#email").attr("placeholder")){
			email = "";
		}

			if(email == null || email == ""){
//				layer.tips('邮箱不能为空', '#email', {
//				    tips: 3,
//				    time:1000
//				});
//				return false;
				return true;
			}else{
				if(!emailReg.test(email)){
					layer.tips('邮箱格式错误，请填写正确格式的邮箱!', '#email', {
					    tips: 3,
					    time:1000
					});
					return false;
				}else{
					return true;
				}
			}
		
}

var userType = $("#userType").val();
	
if(userType != '' && userType != 0){
	$("#selectedDiv").css("margin-top","30px");
}

function searchRole(){
	var keyword = $("#search_condition").val();
	userType = $("#userType").val();
	if(userType == '') {
		layer.tips('请选择用户类型', '#userType', {
		    tips: 3,
		    time:1000
		});
		return;
	}
	$.ajax({
		type : "POST",
		url : ctx + "/user/getRoleList",
		cache : false,
		dataType : 'json',
		data: {
			userId : $("#userId").val(),
			userType : userType,
			keyword : keyword
		},
		success : function(result) {
			if (result.success) {
			      var jsonObj=eval("("+result.obj+")");  
			      $("#userRoles").html("");
			        $.each(jsonObj, function (i, item) {
			        	
			        	var html = '<div style="height:40px;line-height:40px;float:left;"><div style="display:inline-block;float:left;">';
			        	html += '<input id="checked" type="hidden" value=' + item.id + '>';
			        	html += '<input id="checked1" type="hidden" value=' + item.roleName + '>';
			        	html += '<input id="roleLen" type="hidden" value='+ jsonObj.length +'>';
			        	if(item.disabled){
			        		html += '<input type="checkbox" style="vertical-align:middle;cursor: pointer;margin-top:-1px;" onclick="checkRu('+item.id +','+"'"+item.roleName +"'"+','+'this'+',' + item.disabled + ');" id="rStatus'+item.id+'" disabled="disabled"/>';
			        	}else{
			        		html += '<input type="checkbox" style="vertical-align:middle;cursor: pointer;margin-top:-1px;" onclick="checkRu('+item.id +','+"'"+item.roleName +"'"+','+'this'+',' + item.disabled + ');" id="rStatus'+item.id+'"/>';
				        }
			        	html += '</div><div style="vertical-align:middle;float:left;padding-left:5px;">'+item.roleName+'</div></div>';
			        	/*if(i % 2 == 1){
			        		html += '<span></br></span>';
			        	}*/
			        	$("#userRoles").append(html);
			        	
			        	//根据条件过滤角色，selectRu数组包含以选中的角色，遍历它，如果当前列表的id在其中，则说名该角色被选中
			        	for(var i = 0;i < selectRu.length;i++){
			        		if(selectRu[i] == item.id){
			        			$("#rStatus" + item.id).attr("checked","checked");
			        		}
			        	}
						
			        }); 
			} else {
				layer.msg("操作失败",{
					icon: 2
				});
			}
		}
	});
}

var len = $("#length").val();
var roleId;
for(var i=0;i < len;i++){
	roleId = $("#userRole"+ i).val();
	selectRu.push(roleId);
}


function checkRu(id,name,target,disabled){
	var check = target.checked;
	var html = '<div style="float:left;" id='+"choosed" + id +"><span style='display:block;border-radius:10px;text-align:center;line-height:35px;height:35px;margin-top:15px;padding-left:15px;margin-left:15px;border:0;background-color:#37ced4;color:white'  >"+name;
		html +='<img onclick="removeRole('+id+',' + disabled + ')" id="all" src="/manage/images/remove.png" style="cursor:pointer;margin-bottom: -1px;margin-left: 10px;padding-right:10px"/></span></div>';
	if(check){
		selectRu.push(id);

		if(userType == 4){
			$("#choosedRole").html("");
		}

		$("#choosedRole").append(html);
		
	}else{
		for(var i = 0;i < selectRu.length;i++){
			if(selectRu[i] == id){
				selectRu.splice(i,1);
			}
		}
		$("#choosed"+id).remove();
	}
	
	parent.$("#selectedShopId").val("");
}

//反选角色，并且将其移除角色列表
function removeRole(id , disabled){
	if(disabled){
		return;
	}
	for(var i = 0;i < selectRu.length;i++){
		if(selectRu[i] == id){
			selectRu.splice(i,1);
		}
	}
	$("#rStatus"+id).attr("checked",false);
	$("#choosed"+id).remove();
	
	parent.$("#selectedShopId").val("");
}

//新增或编辑会员地址(1:新增 2:编辑)
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
function saveOrUpdateUser (){
	var uname = $("#uname").val();
	var nickname = $("#nickname").val();
	var sex = $("input:radio[name=sex]:checked").val(); 
	var phone = $("#phone").val();
	var email = $("#email").val();
	var userId = $("#userId").val();
	var companyId;
	var rId = $("#role").val();
	var userType = $("#userType").val();
	var selectedShopId = parent.$("#selectedShopId").val();
	
	if(userType == 1){
		companyId = $("#operationCompanyId").val();
	}else if(userType == 2){
		companyId = $("#proCompanyId").val();
	}else if(userType == 3){
		companyId = $("#shopId").val();
	}else if(userType == 4){
		companyId = $("#disCompanyId").val();
	}

	if(checkUserName() && checkPhone() && checkEmial() && checkRole() && checkShop()){
		var index1 = layer.load(1);
	
			$.post(ctx+"/user/editUser",
				{
			uname:uname,
			nickname:nickname,
			sex:sex,
			phone:phone,
			email:email,
			orgId:0,
			id : userId,
			rId:rId,
			roles:selectRu,
			userType : userType,
			companyId : companyId,
			shopIds : [selectedShopId]
				},function(data){
					data = JSON.parse(data);
					if(data.success){
						if(data.obj != null && data.obj == userId){
	    					parent.layer.alert('当前角色权限已被修改，必须重新登陆!', {
	    					    skin: 'layui-layer-molv' //样式类名
	    					    ,closeBtn: 0
	    					}, function(index){
	    						$.get(ctx + "/exist",{},function(data){
	    							data = JSON.parse(data);
	    							if(data.success){
	    								parent.location.href = ctx;
	    							}
	    						});
	    					});
	    				}else{
	    					layer.msg("操作成功",{
								icon: 1,
								time: 1000 //2秒关闭（如果不配置，默认是3秒）
							},function(){
								parent.loadContent("/user/userList?userType=" + userType);
								parent.layer.close(index); //根据窗口索引关闭窗口   
							});
	    				}
						
						
					} else {
						layer.close(index1);
						layer.msg(data.msg,{
							icon: 2,
							time: 1000 //2秒关闭（如果不配置，默认是3秒）
						},function(){
							//parent.layer.close(index); //根据窗口索引关闭窗口   
						});
					}
			});
	}
}

function chooseShop(userId){
	parent.chooseShop(userId,selectRu);
}